<?php
namespace Admin\Controller;

class TaskController extends AdminController
{
    protected function _initialize()
    {
		parent::_initialize ();
	}

	/**
	 * [mass 群发催收短信]
	 * @return [type] [description]
	 */
	public function mass()
	{
		$whotels = M('overdue o')->field('u.telephone,u.user_name,o.urge_day')->where(['task_status' => 0])->join('app_user u on u.identity_no = o.indenty_no')->select();

		foreach ($whotels as $_v)
		{
			$strParams[] = $_v['telephone'].','.mb_substr($_v['user_name'],0,1).','.$_v['urge_day'];
		}

		$post_data = array();
		$post_data['userid']    = 2498;
		$post_data['account']   = 'WEB-A2498-2498';
		$post_data['password']  = '963852';
		$post_data['msg']       = '【车贷中心】尊敬的{$var}先生/女士，您好！您的本期车贷款至今未存，请于本月{$var}日前及时还款，以免将影响到您的个人征信，如已还款本信息仅供参考。咨询热线0571-28106301。退订回T';
		$post_data['params']    = implode($strParams,';');
		$post_data['json']      = 1;
		$post_data['sendtime']  = ''; //不定时发送值为空，定时发送，输入格式YYYY-MM-DD HH：mm：ss的日期值
		$url='http://client.movek.net:8888/sendvarsms.aspx?action=var';
		$o='';
		foreach ($post_data as $k=>$v)
		{
		   $o.="$k=".urlencode($v).'&';
		}
		$post_data=substr($o,0,-1);
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_HEADER, 0);
		curl_setopt($ch, CURLOPT_URL,$url);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //如果需要将结果直接返回到变量里，那加上这句。
		$result = curl_exec($ch);

		$retSend = json_decode($result,true);
		$this->display();
		exit();
	}

	/**
	 * [导入逾期报表]
	 * @return [json] [操作提示]
	 * @author [NYJ]
	 */
	public function add()
	{
		if (IS_POST)
		{
			$_tmpFilename     = '';//$_FILES['tmp_name'];

			$upload           = new \Think\Upload();// 实例化上传类
			$upload->maxSize  = 3145728 ;// 设置附件上传大小
			$upload->exts     = array('xlsx', 'xls', 'csv');// 设置附件上传类型
			$upload->rootPath = './Uploads/'; // 设置附件上传根目录
			$upload->savePath = ''; // 设置附件上传（子）目录
			// 上传文件
			$info   =   $upload->upload();

			// 上传失败返回错误提示
			if (!$info)
			{
				$this->error($upload->getError());
			}

			$info['status'] = 1;

			$_tmpFilename = './Uploads/'.$info['overdue_excel']['savepath'].$info['overdue_excel']['savename'];

			include VENDOR_PATH . 'PHPExcel/PHPExcel.php';

			$type = strtolower($info['overdue_excel']['ext']);
			if($type == 'xlsx' || $type == 'xls' )
			{
		        $objReader = \PHPExcel_IOFactory::createReader('Excel2007'); // 读取 excel 文档
		    }
		    else if( $type=='csv' )
		    {
		        $objReader = \PHPExcel_IOFactory::createReader('CSV'); // 读取 excel 文档
		    }
		    else
		    {
				$this->error('Not supported file types!');
		    }

			$objReader->setReadDataOnly(true);
			$objPHPExcel        = $objReader->load($_tmpFilename);
			$objWorksheet       = $objPHPExcel->getActiveSheet();
			$highestRow         = $objWorksheet->getHighestRow();
			$highestColumn      = $objWorksheet->getHighestColumn();
			$highestColumnIndex = \PHPExcel_Cell::columnIndexFromString($highestColumn);
			$temp  = array();
			$mixed  = array();

			for ($row = 1; $row <= $highestRow; $row++)//行数是以第1行开始
			{
			    for ($column = 0; $column < $highestColumnIndex; $column++) //列数是以A列开始
			    {
					$temp[$row][] = $objWorksheet->getCellByColumnAndRow($column,$row)->getValue();

					if ($column == 2)
					{
						$mixed[$objWorksheet->getCellByColumnAndRow(0,$row)->getValue()] = $objWorksheet->getCellByColumnAndRow($column,$row)->getValue();
					}

			    }
			}

			unset($temp[1]);//剔除表头
			unset($mixed['证件号码']);//剔除表头

			if ($_POST['is_add'])
			{
				$allotRet = $this->allotUser($mixed,[4,5,10]);

				$_successNum = 0;
				foreach ($temp as $_v)
				{
					$_tmpUser = $this->getInfo('id','user',['identity_no' => $_v[0]]);
					if (!is_null($_tmpUser))
					{
						$_tmpData = ['user_id' => $_tmpUser['id'],'indenty_no' => $_v[0],'bank_card' => $_v[1],'overdue_month' => $_v[3],
				       				'overdue_money' => $_v[2],'urge_day' => $_v[4],'update_time' => time(),'create_time' => time()];
				        $this->updateData($_tmpData,'overdue');

				        $_successNum++;
					}
				}

				foreach ($allotRet as $key => $_v)
				{
					$strOverdueMoeny = implode(',',$_v);
					$cap[$key] = $strOverdueMoeny;
					M('overdue')->where('overdue_money in ('.$strOverdueMoeny.')')->data(['admin_id' => $key])->save();
				}

//
				if ($_successNum < count($temp))
				{
					$this->error('此次有部分记录没能导入系统，原因是这些用户在原本系统中不存在，请添加申请后再导入');
				}

				$this->success('此次操作导入'.$_successNum.'条',U('Task/add'));
			}else
			{
				$_successModifyNum = 0;
				// 全部更新
				M('overdue')->data(['task_status' => 1])->where('1 = 1')->save();
				foreach ($temp as $_v)
				{
					$_tmpUser = $this->getInfo('id','user',['identity_no' => $_v[0]]);
					if (!is_null($_tmpUser))
					{
						$_whereData = ['user_id' => $_tmpUser['id'],'indenty_no' => $_v[0],'bank_card' => $_v[1],
				       				'overdue_money' => $_v[2]];

				       	$upRet = M('overdue')->data(['task_status' => 0])->where($_whereData)->save();

				       	if ($upRet)
				       	{
				        	$_successModifyNum++;
				       	}

					}
				}

				if ($_successModifyNum < count($temp))
				{
					$this->error('此次有部分记录没能导入系统，原因是这些用户在原本系统中不存在，请添加申请后再导入');
				}

				$this->success('此次操作更新'.$_successModifyNum.'条',U('Task/add'));
			}

		}
		$this->display();
	}

	/**
	 * [导入代偿报表]
	 * @return [json] [操作提示]
	 * @author [NYJ]
	 */
	public function addUrge()
	{
		if (IS_POST)
		{
			$_tmpFilename     = '';//$_FILES['tmp_name'];

			$upload           = new \Think\Upload();// 实例化上传类
			$upload->maxSize  = 3145728 ;// 设置附件上传大小
			$upload->exts     = array('xlsx', 'xls', 'csv');// 设置附件上传类型
			$upload->rootPath = './Uploads/'; // 设置附件上传根目录
			$upload->savePath = ''; // 设置附件上传（子）目录
			// 上传文件
			$info   =   $upload->upload();

			// 上传失败返回错误提示
			if (!$info)
			{
				$this->error($upload->getError());
			}

			$info['status'] = 1;

			$_tmpFilename = './Uploads/'.$info['overdue_excel']['savepath'].$info['overdue_excel']['savename'];

			include VENDOR_PATH . 'PHPExcel/PHPExcel.php';

			$type = strtolower($info['overdue_excel']['ext']);
			if($type == 'xlsx' || $type == 'xls' )
			{
		        $objReader = \PHPExcel_IOFactory::createReader('Excel2007'); // 读取 excel 文档
		    }
		    else if( $type=='csv' )
		    {
		        $objReader = \PHPExcel_IOFactory::createReader('CSV'); // 读取 excel 文档
		    }
		    else
		    {
				$this->error('Not supported file types!');
		    }

			$objReader->setReadDataOnly(true);
			$objPHPExcel        = $objReader->load($_tmpFilename);
			$objWorksheet       = $objPHPExcel->getActiveSheet();
			$highestRow         = $objWorksheet->getHighestRow();
			$highestColumn      = $objWorksheet->getHighestColumn();
			$highestColumnIndex = \PHPExcel_Cell::columnIndexFromString($highestColumn);
			$temp  = array();

			for ($row = 1; $row <= $highestRow; $row++)//行数是以第1行开始
			{
			    for ($column = 0; $column < $highestColumnIndex; $column++) //列数是以A列开始
			    {
					$temp[$row][] = $objWorksheet->getCellByColumnAndRow($column,$row)->getValue();
			    }
			}

			unset($temp[1]);//剔除表头

			$_successModifyNum = 0;
			foreach ($temp as $_v)
			{
				$_tmpUser = $this->getInfo('id','user',['identity_no' => $_v[0]]);
				if (!is_null($_tmpUser))
				{
					$_whereData = ['indenty_no' => $_v[0],'bank_card' => $_v[1]];

			       	$upRet = M('overdue')->data(['task_status' => 2,'update_time' => time(),'replace_money' => $_v[2],'replace_time' => $_v[3]])->where($_whereData)->save();

			       	if ($upRet)
			       	{
			        	$_successModifyNum++;
			       	}

				}
			}

			if ($_successModifyNum < count($temp))
			{
				$this->error('此次有部分记录没能导入系统，原因是这些用户在原本系统中不存在，请添加申请后再导入');
			}

			$this->success('此次操作更新'.$_successModifyNum.'条',U('Task/addUrge'));
		}
		$this->display();
	}

	// 逾期详情
	public function detail()
	{
		$strId = $_GET["indenty_no"];
		$overdueList=$this->getList('o.*,u.user_name', 'overdue o','o.indenty_no = '.$strId,'','','left join app_user u on o.indenty_no = u.identity_no ');
		$this->assign('list',$overdueList);
		$this->display();
	}

	public function log()
	{
		$nOverdueId =  I('get.overdue_id','','intval');

		$_overdueLogs = $this->getList('ol.*,ads.name','overdue_log ol',['ol.overdue_id' => $nOverdueId],'ol.id desc',true,'left join app_admins ads on ads.id = ol.admin_id');

		$this->assign('overdueLogs',$_overdueLogs);

		$this->display();
	}

	public function index()
	{
		$Overdue  = M('overdue'); // O例化overdue对象
		$groupSql = $Overdue->field('indenty_no,count(id)')->group('indenty_no')->buildSql();// 查询满足要求的总记录数
		$count    = D()->table("{$groupSql} as t")->count();
		$Page     = new \Think\Page($count,15);// 实例化分页类 传入总记录数和每页显示的记录数(25)
		$show     = $Page->show();// 分页显示输出
		// 进行分页数据查询 注意limit方法的参数要使用Page类的属性
		$list = $Overdue->field('indenty_no,count(id) count_num,sum(overdue_money) sum_money')->group('indenty_no')->limit($Page->firstRow.','.$Page->listRows)->select();

		foreach ($list as &$_v)
		{
			$_tmpUser = $this->getInfo('u.user_name,u.telephone,u.loan_bank_card,ci.month_repayment,ci.term','user u',['identity_no' => $_v['indenty_no']],'left join app_car_info ci on ci.user_id = u.id');

			$_v['user_name']       = $_tmpUser['user_name'];
			$_v['telephone']       = $_tmpUser['telephone'];
			$_v['loan_bank_card']  = $_tmpUser['loan_bank_card'];
			$_v['month_repayment'] = $_tmpUser['month_repayment'];
			$_v['term']            = $_tmpUser['term'];
		}

		$this->assign('list',$list);// 赋值数据集
		$this->assign('page',$show);// 赋值分页输出
		$this->display(); // 输出模板
	}

	public function point()
	{
		$nPage        = isset($_GET['p'])? intval($_GET['p']) : 1;
		$overdueModel = M('overdue o');
		$pagesize     = 15;#每页数量
		$offset       = $pagesize * ($nPage - 1);//计算记录偏移量
		$prefix       = C('DB_PREFIX');
		// $loanType  = isset($_GET['loanType']) ? $_GET['loanType'] : 0;
		$order        = isset($_GET['order']) ? $_GET['order'] : 'DESC';

		$strWhere     = 'task_status != 1';
		$count        = $overdueModel->where($strWhere)->count();

		$list  = $overdueModel
			->where($strWhere)
			->field('o.*,u.telephone,u.user_name,a.name')
			->order('o.id desc')
			->limit($offset . ',' . $pagesize)
			-> join('left join app_admins a on o.admin_id = a.id ')
			-> join('left join app_user u on o.indenty_no= u.identity_no ')
			->select();

		$page = new \Think\Page($count, $pagesize);
        $page = $page->show();
        $this->assign('list', $list);
        $this->assign('page', $page);
		$this->display();
	}

	protected function getTasks($p_task_status = null)
	{
		$strWhere = 'task_status != 4';
		if (!is_null($p_task_status))
		{
			$strWhere = 'task_status = '.$p_task_status;
		}

		$list = $this->getList('*','overdue',$strWhere,'id desc',true);
		$this->assign('list',$list);
		$this->display();
	}

	// 电催
	public function tele()
	{
		$nPage       = isset($_GET['p'])? intval($_GET['p']) : 1;
		$overdueModel   = M('overdue');
		$pagesize    = 15;#每页数量
		$offset      = $pagesize * ($nPage - 1);//计算记录偏移量
		$prefix      = C('DB_PREFIX');
		$loanType    = isset($_GET['loanType']) ? $_GET['loanType'] : 0;
		$order       = isset($_GET['order']) ? $_GET['order'] : 'DESC';

		$admin_id = session('adminInfo.id');
		if($admin_id==1){
			$strWhere = '1=1';
		} else {
			$strWhere = 'task_status = 0 and admin_id = '.$admin_id;
		}
		$list = $this->getList('*','overdue',$strWhere,'id desc',true);

		$count = $overdueModel->where($strWhere)->count();

		$list  = $overdueModel
			->where($strWhere)
			->order('id desc')
			->limit($offset . ',' . $pagesize)
			->select();

		$page = new \Think\Page($count, $pagesize);
        $page = $page->show();
        $this->assign('list', $list);
        $this->assign('page', $page);
		$this->display();
	}

	// 外催
	public function out()
	{
		$nPage       = isset($_GET['p'])? intval($_GET['p']) : 1;
		$overdueModel   = M('overdue');
		$pagesize    = 15;#每页数量
		$offset      = $pagesize * ($nPage - 1);//计算记录偏移量
		$prefix      = C('DB_PREFIX');
		$loanType    = isset($_GET['loanType']) ? $_GET['loanType'] : 0;
		$order       = isset($_GET['order']) ? $_GET['order'] : 'DESC';

		$admin_id = session('adminInfo.id');
		$strWhere = 'task_status !=1 and pull_status = 1 ';
		$list = $this->getList('*','overdue',$strWhere,'id desc',true);

		$count = $overdueModel->where($strWhere)->count();

		$list  = $overdueModel
			->where($strWhere)
			->order('id desc')
			->limit($offset . ',' . $pagesize)
			->select();

		$page = new \Think\Page($count, $pagesize);
        $page = $page->show();
        $this->assign('list', $list);
        $this->assign('page', $page);
		$this->display();
	}

	// 法务
	public function justice()
	{
		$nPage       = isset($_GET['p'])? intval($_GET['p']) : 1;
		$overdueModel   = M('overdue');
		$pagesize    = 15;#每页数量
		$offset      = $pagesize * ($nPage - 1);//计算记录偏移量
		$prefix      = C('DB_PREFIX');
		$loanType    = isset($_GET['loanType']) ? $_GET['loanType'] : 0;
		$order       = isset($_GET['order']) ? $_GET['order'] : 'DESC';

		$admin_id = session('adminInfo.id');
		$strWhere = 'task_status = 2 ';
		$list = $this->getList('*','overdue',$strWhere,'id desc',true);

		$count = $overdueModel->where($strWhere)->count();

		$list  = $overdueModel
			->where($strWhere)
			->order('id desc')
			->limit($offset . ',' . $pagesize)
			->select();

		$page = new \Think\Page($count, $pagesize);
        $page = $page->show();
        $this->assign('list', $list);
        $this->assign('page', $page);

		$this->display();
	}

	// 提交反馈
	public function telbak()
	{
		if (IS_POST)
		{
			$nOverdueId   = $_POST['overdue_id'];
			$nExecuteType = $_POST['execute_type'];
			$strFeedback  = $_POST['feedback'];
			$nAdminId     = session('adminInfo.id');

			$_tmpOverdue = $this->getInfo('*','overdue',['id' => $nOverdueId]);

			$overdueLog = ['task_status' => $_tmpOverdue['task_status'],'overdue_id' => $nOverdueId,'execute_type' => $nExecuteType,
							'feedback' => $strFeedback,'admin_id' => $nAdminId,'create_time' => time()];

			$ret = $this->updateData($overdueLog,'overdue_log');

			$this->updateData(['task_status' => 0,'update_time' => time()],'overdue',['id' => $nOverdueId],2);

			if ($ret)
			{
				echo $ret;
			}else
			{
				$tips = ['message' => '数据库异常，请联系管理员','status' => 0];
				echo json_encode($tips);
			}
		}
	}

	//指派拖车任务
	public function pointTask()
	{
		if (IS_POST)
		{
			$nId         = $_POST['overdue_id'];
			// $task_status = $_POST['task_status'];

			$_tmpOverdue = $this->getInfo('*','overdue',['id' => $nId]);

			if ($_tmpOverdue['status'] != 1 )
			{
				echo $this->updateData(['pull_status' => 1, 'update_time' => time()],'overdue',2,['id' => $nId]);
			}else{
				$tips = ['message' => '该逾期记录不存在或者数据有问题','status' => 0];
				echo json_encode($tips);
			}
			exit();
		}
	}

	//查看反馈结果
	public function feedback()
	{
		$overdue_id = $_GET["overdue_id"];
		$overdue_log = M('overdue_log')
				->where(['overdue_id'=>$overdue_id])
				->join('left join app_admins on app_admins.id=app_overdue_log.admin_id')
				->select();
		$this->assign('overdue_log',$overdue_log);
		$this->assign('overdue_id',$overdue_id);
		$this->display();
	}

	public function finishTask()
	{
		if (IS_POST)
		{
			$nId = $_POST['overdue_id'];

			$_tmpOverdue = $this->getInfo('*','overdue',['id' => $nId]);

			if ($_tmpOverdue['status'] == 0)
			{
				echo $this->updateData(['task_status' => 4, 'update_time' => time()],'overdue',2,['id' => $nId]);
			}else{
				$tips = ['message' => '该逾期记录不存在或者数据有问题','status' => 0];
				echo json_encode($tips);
			}
			exit();
		}
	}

	/**
	 * 逻辑  先循环左边，最小放到数组（最大值 KEY）里面去，其次循环右边最大（最小值 KEY）放到数组
	 * [allotUser 平均分配]
	 * @param  array  $numbers [description]
	 * @param  array  $users   [description]
	 * @return [type]          [description]
	 */
	protected function allotUser ($numbers = [], $users = [])
	{
		sort($numbers);

		$newArr = [];

		$left = 0;
		$right = count($numbers)-1;
		$stage = count($users);

		$index = 0;
		$type = false;

		$arrIndex = 0;
		while ($index < count($numbers))
		{
			if($index%$stage===0)
			{
				$type = !$type;
				$arrIndex = 0;
			}

			if($type)
			{
				$leftValue = $numbers[$left];
				$newArr[$arrIndex][] = $leftValue;
				$left++;
			}
			else
			{
				$rightValue = $numbers[$right];
				$newArr[$arrIndex][] = $rightValue;
				$right--;
			}
			$index++;
			$arrIndex++;
		}

		$userList = [];
		foreach ($newArr as $key => $value)
		{
			$userList[$users[$key]] = array_values($value);
		}
		return $userList;
	}
}